<template>
  <div class="post-video-container">
    <div class="post-video-body">
      <!-- 进度条 -->
      <div v-if="uploadProgress > 0" class="upload-progress">
        <progress :value="uploadProgress" max="100">
          {{ uploadProgress }}%
        </progress>
      </div>
      <button @click="pauseUpload" v-if="isUploading">暂停上传</button>
      <button @click="resumeUpload" v-if="!isUploading && !uploadCompleted">
        继续上传
      </button>
      <button @click="cancelUpload" v-if="!uploadCompleted">取消上传</button>
    </div>

    <div class="video-form">
      <div class="video-thumbnail" v-if="videoInfo.url">
        <div class="video-thumbnail-text">封面</div>
        <div class="video-thumbnail-img">
          <img :src="thumbnailBase64" alt="" />
        </div>
      </div>
      <div class="video-title">
        <div class="video-title-text">标题</div>
        <div class="video-title-input">
          <input
            type="text"
            v-model="videoInfo.title"
            maxlength="80"
            placeholder="请输入标题"
            class="input-val"
          />
        </div>
      </div>
      <div class="video-type">
        <div class="video-type-text">类型</div>
        <div class="video-type-selector">
          <el-radio-group v-model="videoInfo.type">
            <el-radio value="1">原创</el-radio>
            <el-radio value="2">转载</el-radio>
          </el-radio-group>
        </div>
      </div>
      <div class="video-area">
        <div class="video-area-text">分区</div>
        <div class="video-area-selector">
          <el-select v-model="videoInfo.area" placeholder="请选择分区">
            <el-option
              v-for="area in areas"
              :key="area.value"
              :label="area.label"
              :value="area.value"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="video-tag">
        <div class="video-tag-container">
          <div class="video-tag-text">标签</div>
          <div class="video-tag-input">
            <input
              type="text"
              maxlength="80"
              placeholder="按回车Enter键创建标签"
              class="input-val"
              ref="tagInput"
              @keyup.enter="createTag"
            />
          </div>
        </div>
        <div class="video-tag-show" v-if="videoInfo.tags.length > 0">
          <el-tag
            type="info"
            v-for="(tag, index) in videoInfo.tags"
            :key="index"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
      <div class="video-description">
        <div class="video-description-text">简介</div>
        <div class="video-description-input">
          <input
            type="text"
            v-model="videoInfo.description"
            placeholder="请输入简介"
            class="input-val"
            maxlength="80"
          />
        </div>
      </div>
      <div class="submit-video">
        <el-button @click="postVideo" type="primary">立即投稿</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  transferVideoFile,
  uploadVideo,
} from '@/api/front/video/videoController'
import uploadVideoParams = API.uploadVideoParams

// 假设这里有一个用于上传文件的 API 函数
// 接收父组件传递的属性
const props = defineProps<{
  uploadId: string
  file: File | null
  chunkCount: number
}>()
const CHUNK_SIZE = 3 * 1024 * 1024 // 每个分片大小为3MB
// 事件发射器
const emit = defineEmits(['upload-completed', 'upload-cancelled'])
onMounted(() => {
  if (props.file && props.chunkCount > 0) {
    startUpload()
  }
})
// 上传状态
const isUploading = ref(false)
const uploadCompleted = ref(false)
const uploadProgress = ref(0)
const currentChunkIndex = ref<number>(1)
const startUpload = async () => {
  // 如果文件存在且还没有完成上传，则开始上传
  if (!uploadCompleted.value && props.file && props.chunkCount > 0) {
    uploadCompleted.value = false
    isUploading.value = true
    try {
      await uploadNextChunk() // 开始分片上传
    } catch (error) {
      console.error('上传失败:', error)
    } finally {
      isUploading.value = false
    }
  }
}

// 分片上传逻辑
const uploadNextChunk = async () => {
  if (currentChunkIndex.value >= props.chunkCount || uploadCompleted.value)
    return

  isUploading.value = true

  const blob = props.file?.slice(
    currentChunkIndex.value * CHUNK_SIZE,
    (currentChunkIndex.value + 1) * CHUNK_SIZE,
  )
  // 构建 FormData 对象
  const formData = new FormData()
  if (blob && props.file) {
    try {
      // 为每个分片创建一个唯一的文件名
      formData.append('file', blob, `${currentChunkIndex.value}`) // 添加文件分片并指定文件名
      formData.append('chunkIndex', currentChunkIndex.value.toString()) // 添加分片索引
      formData.append('uploadId', props.uploadId) // 添加上传 ID

      // 调用后端上传接口
      const response = await uploadVideo(formData) // 强制类型转换

      if (response.data.code === '0') {
        currentChunkIndex.value++
        uploadProgress.value = Math.min(
          100,
          (currentChunkIndex.value / props.chunkCount) * 100,
        )

        if (currentChunkIndex.value < props.chunkCount) {
          // 递归调用直到所有分片上传完毕
          await uploadNextChunk()
        } else {
          const params = {
            uploadId: props.uploadId,
          }
          // 所有分片上传完成后合并和转码
          await transferVideoFile(params)
        }
      }
    } catch (error) {
      console.error('分片上传失败:', error)
      ElMessage.error('分片上传失败，请检查网络连接或稍后再试')
      isUploading.value = false
    } finally {
      // 确保在任何情况下都将 isUploading 设置为 false
      isUploading.value = false
    }
  }
}

const pauseUpload = () => {
  isUploading.value = false
}

const resumeUpload = () => {
  if (!isUploading.value && !uploadCompleted.value) {
    isUploading.value = true
    uploadNextChunk()
  }
}

const cancelUpload = () => {
  isUploading.value = false
  uploadCompleted.value = false
  currentChunkIndex.value = 0
  uploadProgress.value = 0
  ElMessage.warning('上传已取消')
}
// 分片上传逻辑
watch(
  () => props.uploadId,
  async (newVal) => {
    if (newVal && props.file) {
      await uploadNextChunk()
    }
  },
)

// 定义变量
const uploadUrl = ref('') // 如果有固定的上传地址可以设置
const color = ref('#606266')
const uploadedFileName = ref('')
const selectedFile = ref<File | null>(null)
const thumbnailBase64 = ref('')
const videoInfo = reactive({
  url: '',
  duration: '',
  thumbnail: '',
  title: '',
  type: '1',
  area: '',
  tags: [],
  description: '',
})
const areas = ref([
  { value: '0', label: '鬼畜' },
  { value: '1', label: '音乐' },
  { value: '2', label: '电影' },
  { value: '3', label: '番剧' },
  { value: '4', label: '游戏' },
])

// 获取封面
const getFrameAtTime = async (file: File) => {
  if (!file) {
    ElMessage.error('没有选择文件')
    return
  }

  const videoUrl = URL.createObjectURL(file)
  const videoElement = document.createElement('video')
  videoElement.src = videoUrl

  await new Promise<void>((resolve) => {
    videoElement.onloadedmetadata = () => {
      videoInfo.duration = videoElement.duration.toString()
      videoElement.currentTime = 0
      videoElement.onseeked = () => {
        const canvas = document.createElement('canvas')
        const context = canvas.getContext('2d')
        if (context) {
          canvas.width = videoElement.videoWidth
          canvas.height = videoElement.videoHeight
          context.drawImage(videoElement, 0, 0, canvas.width, canvas.height)
          thumbnailBase64.value = canvas.toDataURL('image/jpeg')
          resolve()
        }
      }
    }
  })

  if (thumbnailBase64.value) {
    // 将 base64 转换为 Blob 并上传
    const blob = await (await fetch(thumbnailBase64.value)).blob()
    const thumbnailFile = new File([blob], 'thumbnail.jpg', {
      type: 'image/jpeg',
    })
  }
}
</script>

<style scoped lang="scss">
.post-video-container {
  max-width: 830px;
  margin: 0 auto;
  position: relative;
  .post-video-body {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    margin-top: 30px;
    margin-bottom: 30px;
    position: relative;
    color: #999;
    font-size: 14px;
    border: 2px dashed #ccc;
    padding: 30px;
    .el-icon-upload2 {
      font-size: 30px;
    }
    .video-operation-btn {
      margin-top: 20px;
      font-size: 16px;
      margin-left: 0;
    }
    .upload-progress {
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin-top: 20px;
      font-size: 16px;
      margin-left: 0;
    }
  }
  .video-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    .video-thumbnail {
      display: flex;
      .video-thumbnail-text {
        width: 100px;
      }
      .video-thumbnail-img {
        img {
          width: 100%;
          height: auto; /* 自动调整高度以保持比例 */
          max-width: 320px; /* 或者根据设计要求设置最大宽度 */
          max-height: 180px; /* 或者根据设计要求设置最大高度 */
          border-radius: 4px;
        }
      }
    }
  }
  .video-title {
    display: flex;
    justify-content: space-between;
    margin-top: 40px;

    .video-title-text {
      width: 100px;
    }

    .video-title-input {
      border-radius: 4px;
      padding: 0 12px;
      border: 1px solid #ccd0d7;
      min-width: 200px;
      width: 100%;
      .input-val {
        width: 100%;
        border: none;
        color: #222;
        line-height: 22px;
        height: 22px;
        outline: 0;
        border: 0;
        background-color: transparent;
        font-size: 16px;
      }
    }
  }

  .video-type {
    display: flex;
    margin-top: 40px;
    align-items: center;

    .video-type-text {
      width: 100px;
    }
    .video-type-selector {
      display: flex;
    }
  }

  .video-area {
    display: flex;
    margin-top: 40px;
    align-items: center;

    .video-area-text {
      width: 100px;
    }
    .video-area-selector {
      display: flex;
    }
  }

  .video-tag {
    display: flex;
    margin-top: 40px;
    flex-direction: column;

    .video-tag-container {
      display: flex;
      align-items: center;
      .video-tag-text {
        width: 100px;
      }
      .video-tag-input {
        border-radius: 4px;
        padding: 0 12px;
        border: 1px solid #ccd0d7;
        min-width: 200px;
        width: 100%;
        .input-val {
          width: 100%;
          border: none;
          color: #222;
          line-height: 22px;
          height: 22px;
          outline: 0;
          border: 0;
          background-color: transparent;
          font-size: 16px;
        }
      }
    }
    .video-tag-show {
      margin-right: 5px;
    }
  }

  .video-description {
    display: flex;
    justify-content: space-between;
    margin-top: 40px;

    .video-description-text {
      width: 100px;
    }
    .video-description-input {
      border-radius: 4px;
      padding: 0 12px;
      border: 1px solid #ccd0d7;
      min-width: 200px;
      width: 100%;
      height: 60px;
      .input-val {
        width: 100%;
        border: none;
        color: #222;
        line-height: 22px;
        height: 22px;
        outline: 0;
        border: 0;
        background-color: transparent;
        font-size: 16px;
      }
    }
  }

  .submit-video {
    display: flex;
    justify-content: center;
  }
}
</style>
